package io.agora.openduo.activities;

import android.os.Bundle;
import android.widget.Toast;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import io.agora.openduo.MyApp;
import io.agora.openduo.R;
import io.agora.openduo.agora.Config;
import io.agora.openduo.databinding.ActivityDialerBinding;
import io.agora.rtm.ErrorInfo;
import io.agora.rtm.ResultCallback;

public class DialerActivityAgora extends AgoraBaseCallActivity {

    ActivityDialerBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDialerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initUI();
    }

    private void initUI() {
        binding.identifierText.setText(String.format(getResources().
                getString(R.string.identifier_format), MyApp.mConfig.userID));

        binding.call.setOnClickListener(view -> {
            int number = Integer.parseInt(binding.num.getText().toString());
            final String peer = String.valueOf(number);
            Set<String> peerSet = new HashSet<>();
            peerSet.add(peer);

            MyApp.mRtmClient.queryPeersOnlineStatus(peerSet,
                    new ResultCallback<Map<String, Boolean>>() {
                        @Override
                        public void onSuccess(Map<String, Boolean> statusMap) {
                            Boolean bOnline = statusMap.get(peer);
                            if (bOnline != null && bOnline) {
                                String uid = String.valueOf(
                                        MyApp.mConfig.userID);
                                String channel = uid + peer;
                                gotoCallingInterface(peer, channel, Config.ROLE_CALLER);
                            } else {
                                runOnUiThread(() -> Toast.makeText(DialerActivityAgora.this,
                                        R.string.peer_not_online,
                                        Toast.LENGTH_SHORT).show());
                            }
                        }

                        @Override
                        public void onFailure(ErrorInfo errorInfo) {

                        }
                    });
        });
    }
}
